package com.yoyo.generator.util;

import com.yoyo.common.constant.GenConstants;
import com.yoyo.common.utils.StringUtils;
import com.yoyo.generator.config.GenConfig;
import com.yoyo.generator.domain.GenTable;
import com.yoyo.generator.domain.GenTableColumn;
import org.apache.commons.lang3.RegExUtils;

import java.util.Arrays;

/**
 * @author zyl
 * @Date 2021/10/5 -16:57
 */
public class GenUtils {

    public static void initTable(GenTable table, String loginName) {
        table.setClassName(convertClassName(table.getTableName()));
        table.setPackageName(GenConfig.getPackageName());
        table.setModuleName(getModuleName(GenConfig.getPackageName()));
        table.setBusinessName(getBusinessName(table.getTableName()));
        table.setFunctionName(replaceText(table.getTableComment()));
        table.setFunctionAuthor(GenConfig.getAuthor());
        table.setCreateBy(loginName);
    }

    /**
     * 关键替换
     * @param text
     * @return
     */
    public static String replaceText(String text) {
        return RegExUtils.replaceAll(text, "(?:表|YOYO)", "");
    }

    /**
     * 获取业务名
     *
     * @param tableName
     * @return
     */
    private static String getBusinessName(String tableName) {

        return StringUtils.substring(tableName, tableName.lastIndexOf("_") + 1, tableName.length());
    }

    /**
     * 获取模块名称
     *
     * @param packageName
     * @return
     */
    public static String getModuleName(String packageName) {

        return StringUtils.substring(packageName, packageName.lastIndexOf(".") + 1, packageName.length());
    }

    /**
     * 表名换成java类名
     *
     * @param tableName
     * @return
     */
    private static String convertClassName(String tableName) {
        String tablePrefix = GenConfig.getTablePrefix();
        if (GenConfig.getAutoRemovePre() && StringUtils.isNotEmpty(tablePrefix)) {
            String[] searchList = StringUtils.split(tablePrefix, ",");
            tableName = replaceFirst(tableName, searchList);
        }
        return StringUtils.convertToCamelCase(tableName);
    }

    /**
     * 批量替换前缀
     *
     * @param replace
     * @param searchList
     * @return
     */
    public static String replaceFirst(String replace, String[] searchList) {
        String temp = replace;
        for (String search : searchList) {
            if (replace.startsWith(search)) {
                temp = replace.replaceFirst(search, "");
                break;
            }
        }

        return temp;

    }

    /**
     * 初始化 列属性字段
     * @param column 
     * @param table
     */
    public static void initColumnField(GenTableColumn column, GenTable table) {
        String dataType = getDbType(column.getColumnType());
        String columnName = column.getColumnName();
        //设置java字段名
        column.setJavaField(StringUtils.toCamelCase(columnName));
        column.setTableId(table.getTableId());
        column.setCreateBy(table.getCreateBy());
        if(arraysContains(GenConstants.COLUMNTYPE_STR,dataType)) {
            column.setJavaField(GenConstants.TYPE_STRING);
            // 字符串 长度超过500 设置为文本域
            Integer columnLength = getColumnLength(column.getColumnType());
            String htmlType = columnLength >= 500 ? GenConstants.HTML_TEXTAREA : GenConstants.HTML_INPUT;
            column.setHtmlType(htmlType);
        }else if (arraysContains(GenConstants.COLUMNTYPE_TIME,dataType)){
            column.setJavaType(GenConstants.TYPE_DATE);
            column.setHtmlType(GenConstants.HTML_DATETIME);
        }else  if (arraysContains(GenConstants.COLUMNTYPE_NUMBER,dataType)){
            column.setHtmlType(GenConstants.HTML_INPUT);
            // 如果是浮点型
            String[] str = StringUtils.split(StringUtils.substringBetween(column.getColumnType(), "(", ")"), ",");
            if (str !=null && str.length==2 && Integer.parseInt(str[1])>0){
                column.setJavaType(GenConstants.TYPE_BIGDECIMAL);
            }else if (str!=null && str.length ==1 && Integer.parseInt(str[0])<=10){
             // 如果是整形
             column.setJavaType(GenConstants.TYPE_INTEGER);
            }else {
                // 是长整形
                column.setJavaType(GenConstants.TYPE_LONG);
            }

            // 插入字段 （默认所有字段都需要插入）
            column.setIsInsert(GenConstants.REQUIRE);

            // 编辑字段
            if (!arraysContains(GenConstants.COLUMNNAME_NOT_EDIT,columnName) && !column.isPk()){
                column.setIsEdit(GenConstants.REQUIRE);
            }
            // 列表字段
            if (!arraysContains(GenConstants.COLUMNNAME_NOT_LIST,columnName) && !column.isPk()){
                column.setIsList(GenConstants.REQUIRE);
            }
            // 查询字段
            if (!arraysContains(GenConstants.COLUMNNAME_NOT_QUERY,columnName) && !column.isPk()){
                column.setIsQuery(GenConstants.REQUIRE);
            }
            // 查询字段类型
            if (StringUtils.endsWithIgnoreCase(columnName,"name")){
                column.setQueryType(GenConstants.QUERY_LIKE);
            }
            // 状态字段设置单选框
            if (StringUtils.endsWithIgnoreCase(columnName,"status")){
                column.setHtmlType(GenConstants.HTML_RADIO);
            }
            // 类型 性别字段设置下拉框
            else if(StringUtils.endsWithIgnoreCase(columnName,"type")
                    || StringUtils.endsWithIgnoreCase(columnName,"sex")){
                column.setHtmlType(GenConstants.HTML_SELECT);
            }
            // 文件 字段 设置上传控件
            else if (StringUtils.endsWithIgnoreCase(columnName,"file")){
                column.setHtmlType(GenConstants.HTML_UPLOAD);
            }
            // 内容 字段 设置富文本控件
            else if (StringUtils.endsWithIgnoreCase(columnName,"content")){
                column.setHtmlType(GenConstants.HTML_SUMMERNOTE);
            }
        }
    }

    /**
     * 获取字段长度
     * @param columnType 列类型
     * @return 截取后的列类型
     */
    private static Integer getColumnLength(String columnType) {
        if (StringUtils.indexOf(columnType, "(") > 0) {
            return Integer.valueOf(StringUtils.substringBetween(columnType, "(", ")"));
        } else {
            return 0;
        }
    }

    /**
     * 校验数组是否包含指定值
     * @param arr
     * @param targetValue
     * @return
     */
    private static boolean arraysContains(String[] arr, String targetValue) {
        return Arrays.asList(arr).contains(targetValue);
    }

    /**
     * 获取数据库类型字段
     * @param columnType
     * @return
     */
    private static String getDbType(String columnType) {
        if (StringUtils.indexOf(columnType, "(") > 0) {
            return StringUtils.substringBefore(columnType, "(");
        } else {
            return columnType;
        }
    }
}
